﻿using Smile.Network.Http;
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Threading.Tasks;
using Windows.Phone.System.UserProfile;

namespace Smile.Mvvm.Service
{
    /// <summary>Service which manage interaction with operating system lock screen.</summary>
    public class LockScreenService : ILockScreenService
    {
        // @Poperties
        public bool CanSetLockScreen
        {
            get 
            {
                return _canSetLockScreen;
            }
        }

        public bool IsPair
        {
            get
            {
                return _isPair;
            }
            private set
            {
                _isPair = value;
                ServiceLocator
                    .Retrieve<ISettingsService>()
                    .Add(_pairKey, value);
            }
        }


        // @Public
        public LockScreenService()
        {
            bool isPair;
            if (ServiceLocator.Retrieve<ISettingsService>()
                    .TryGetValue(_pairKey, out isPair))
            {
                IsPair = isPair;
            }
        }

        public async Task<bool> AuthorizeLockScreenAsync()
        {
            var op = await LockScreenManager.RequestAccessAsync();
            _canSetLockScreen = (op == LockScreenRequestResult.Granted);
            return _canSetLockScreen;
        }

        public void SetLockScreenAsync(string uriString)
        {
            SetLockScreenAsync(new Uri(uriString, UriKind.Absolute));
        }

        public async void SetLockScreenAsync(Uri uri)
        {
            if (CanSetLockScreen)
            {
                // Gettting the image
                HttpRequest request = new HttpRequest();
                var response = await request.GetAsync(uri);

                if (response.Status == HttpStatusCode.OK)
                {
                    SetLockScreenAsync(response.ContentBytes);
                }
            }
        }

        public async void SetLockScreenAsync(byte[] buffer)
        {
            if (CanSetLockScreen)
            {
                // Saving Picture
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(
                    GetFilename(),
                    FileMode.Create,
                    IsolatedStorageFile.GetUserStoreForApplication()))
                {
                    using (var ms = new MemoryStream(buffer))
                    {
                        await ms.CopyToAsync(stream);
                    }
                }


                // Updating LockScreen
                var imageUri = new Uri("ms-appdata:///Local/" + GetFilename(), UriKind.Absolute);

                LockScreen.SetImageUri(imageUri);
                IsPair = !IsPair;
            }
        }


        // @Private
        const string    _pairKey = "LockscreenPairKey";
        bool            _isPair = false;
        bool            _canSetLockScreen = LockScreenManager.IsProvidedByCurrentApplication;

        string GetFilename()
        {
            if (IsPair)
            {
                return "LockScreen_A";
            }
            else
            {
                return "LockScreen_B";
            }
        }
    }
}
